package com.lyn.chapter2.demo1;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class RequestIDGenerator implements CircularSeqGenerator {
	private final static RequestIDGenerator INSTANCE = new RequestIDGenerator();
	private final static short SEQ_UPPER_LIMIT = 999;
	private short sequence = -1; //多个线程并发的访问同一个实例变量，导致静态
	
	private RequestIDGenerator() {}
	
	public static RequestIDGenerator getInstance() {
		return INSTANCE;
	}
	
	@Override
	public short nextSequence() {
	//public synchronized short nextSequence() {
		if(sequence>=SEQ_UPPER_LIMIT) {
			sequence = 0;
		} else {
			sequence++;
		}
		return sequence;
	}
	
	public String nextID() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
		String timestamp = sdf.format(new Date());
		DecimalFormat df = new DecimalFormat("000");
		
		//生成请求序列号
		short sequenceNO = nextSequence();
		return "0049" +timestamp+df.format(sequenceNO);
	}
	
	
}
